<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" style="border-bottom: 1px solid #c9c9c9;margin-bottom: 30px;"
      :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="等级名称" prop="levelName">
        <el-input v-model="queryParams.levelName" placeholder="请输入等级名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item style="width: 250px;" label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" style="background-color: #266FE8; color: white;"
          @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="display: flex; justify-content: flex-end;" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" style="width: 150px; background-color: #266FE8; color: white;" plain icon="Plus"
          @click="handleAdd" v-hasPermi="['level:level:add']">新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="levelList" @selection-change="handleSelectionChange">
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="等级名称" align="center" prop="levelName" />
      <el-table-column label="护理费用" align="center" prop="nursingFee" />
      <el-table-column label="等级说明" align="center" prop="levelDescription" />
      <el-table-column label="创建人" align="center" prop="sysUser.nickName" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" 
          :style="{
            'display': 'inline-block',
            'margin-right': '5px',
            'color': scope.row.status === 0 ? '#c0c4cc' : 'red',  /* 禁用时浅灰，否则红色 */
            'cursor': scope.row.status === 0 ? 'not-allowed' : 'pointer'  /* 鼠标样式 */}" 
          :disabled="scope.row.status == 0" @click="handleDelete(scope.row)"
            v-hasPermi="['system:plan:remove']">删除</el-button>
          <el-button link type="primary"
          :style="{
            'display': 'inline-block',
            'margin-right': '5px',
            'color': scope.row.status === 0 ? '#c0c4cc' : '',  /* 禁用时浅灰，否则红色 */
            'cursor': scope.row.status === 0 ? 'not-allowed' : 'pointer'  /* 鼠标样式 */}" 
          :disabled="scope.row.status == 0"
            @click="handleUpdate(scope.row)" v-hasPermi="['system:plan:edit']">编辑</el-button>
          <el-button link type="primary" :style="{ color: scope.row.status ? 'red' : '', display: 'inline-block' }"
            @click="changeStatus(scope.row)"
            v-hasPermi="['system:plan:edit']">{{ scope.row.status ? '禁用' : '启用' }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改护理等级对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="levelRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="等级名称" :rules="[
          { required: true, message: '请输入等级名称', trigger: 'blur' },
          { max: 10, message: '最多输入10个字符', trigger: 'blur' },
          {
            validator: validateLevelNameUnique, // 自定义重复校验方法
            trigger: ['blur', 'change'] // 失焦+输入变化时都触发，提示更及时
          }
        ]" prop="levelName">
          <el-input v-model="form.levelName" placeholder="请输入等级名称" maxlength="10" />
        </el-form-item>
        <el-form-item style="width: 300px;" label="执行护理计划" prop="status">
          <el-select v-model="form.planId" placeholder="请选择护理计划" clearable @change="handlePlanChange">
            <el-option v-for="dict in plan" :key="dict.id" :label="dict.planName" :value="dict.id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="护理费用" prop="nursingFee">
          <el-input v-model="form.nursingFee" disabled="1" type="number" placeholder="请输入护理费用" />
        </el-form-item> -->
        <el-form-item label="等级说明" prop="levelDescription">
          <el-input v-model="form.levelDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Level">
import { listLevel, getLevel, delLevel, addLevel, updateLevel, selectName } from "@/api/level/level"
import { listPlan } from "@/api/system/plan"
import { listBinding, getBinding, delBinding, addBinding, updateBinding } from "@/api/le/binding"
import { useUserStore } from '@/store/modules/user'

// 使用
const userStore = useUserStore()

const { proxy } = getCurrentInstance()
const { status } = proxy.useDict('status')

const levelList = ref([])
const plan = ref([])
const plan_id = ref(null)
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    levelName: null,
    extraField2: null
  },
  rules: {
    levelName: [
      { required: true, message: "等级名称不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询护理等级列表 */
function getList() {
  loading.value = true
  listLevel(queryParams.value).then(response => {
    levelList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

//获取护理计划列表
function getPlanList() {
  listPlan(queryParams.value).then(response => {
    console.log(response);
    plan.value = response.rows
    // console.log("plan",plan.value);
    
  })
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    levelName: null,
    nursingFee: null,
    levelDescription: null,
    creator: null,
    createTime: null,
    status: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null,
    originalLevelName: undefined // 清空初始名称（关键）
  };
  proxy.resetForm("levelRef");
}
// 自定义校验：判断等级名称是否重复（修改时允许与自身初始名称一致）
function validateLevelNameUnique(rule, value, callback) {
  const currentValue = value.trim();
  // 1. 空值不校验（与必填规则配合）
  if (!currentValue) {
    return callback();
  }

  // 2. 判断是新增还是修改（修改时存在id和初始名称）
  const isEdit = !!form.value.id && form.value.originalLevelName !== undefined;

  // 3. 修改场景：如果名称没改，直接通过校验
  if (isEdit && currentValue === form.value.originalLevelName) {
    return callback();
  }

  // 4. 新增场景 或 修改了名称：调用接口校验是否与其他记录重复
  selectName({ levelName: currentValue }).then(response => {
    if (response.data > 0) {
      callback(new Error('该等级名称已存在，请更换'));
    } else {
      callback();
    }
  }).catch(() => {
    // 接口请求失败时的容错处理
    callback(new Error('名称校验失败，请重试'));
  });
}

function handlePlanChange(planId) {  
  // 当未选择计划时清空费用
  if (!planId) {
    form.value.nursingFee = null;
    return;
  }
  
  // 从计划列表中找到选中的计划对象
  const selectedPlan = plan.value.find(item => item.id == planId);
  console.log(selectedPlan);
  
  if (selectedPlan && selectedPlan.price) {
    // 同步选中计划的价格到护理费用
    console.log(selectedPlan.price);
    form.value.nursingFee = selectedPlan.price;
  }
}


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加护理等级"
}
// function handleUpdate(row) {
//   reset();
//   const _id = row.id || ids.value;
//   form.value.levelId = _id;
//   getLevel(_id).then(response => {
//     const levelData = response.data;
//     form.value = levelData;
//     // 存储初始名称（关键：用于判断是否修改了名称）
//     form.value.originalLevelName = levelData.levelName;
//     open.value = true;
//     title.value = "修改护理等级";
//   });

//   listBinding({ levelId: _id }).then(response => {
//     console.log(response);

//     form.value.planId = response.rows[0].planId;
//   });

// }
// 修改：处理修改操作时同步计划对应的价格
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  form.value.levelId = _id;
  getLevel(_id).then(response => {
    const levelData = response.data;
    form.value = levelData;
    form.value.originalLevelName = levelData.levelName;
    open.value = true;
    title.value = "修改护理等级";
  });

  listBinding({ levelId: _id }).then(response => {
    console.log(response);
    if (response.rows && response.rows.length > 0) {
      form.value.planId = response.rows[0].planId;
      // 触发价格同步
      handlePlanChange(form.value.planId);
    }
  });
}
/** 提交按钮 */
function submitForm() {
  form.value.creator = userStore.id
  const level_id = 0
  proxy.$refs["levelRef"].validate(valid => {

    if (valid) {
      if (form.value.id != null) {
        updateLevel(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          getList()
        })
        console.log(form.value);

        updateBinding({ levelId: form.value.id, planId: form.value.planId }).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          getList()
        })

      }
      else {
        addLevel(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          console.log(response);
          level_id = response.data
          console.log(form.value);
          getList()
        })
      }
    }
    console.log(form.value);
    open.value = false
  }
  )
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除护理等级编号为"' + _ids + '"的数据项？').then(function () {
    return delLevel(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}
// 禁用启用
function changeStatus(row) {
  const _ids = row.id || ids.value
  console.log("进入修改状态函数");

  const statu = ref(0)
  if (row.status) {
    statu.value = 0
  } else {
    statu.value = 1
  }

  const updateForm = ref({
    id: row.id,
    planName: row.planName,
    creator: row.creator,
    createTime: row.createTime,
    extraField1: row.extraField1,
    extraField2: row.extraField2,
    isDeleted: row.isDeleted,
    status: statu.value
  })
  if (row.status) {
    proxy.$modal.confirm('是否确认禁用护理计划编号为"' + _ids + '"的数据项？').then(function () {
      updateLevel(updateForm.value).then(response => {
        proxy.$modal.msgSuccess("修改成功")
        open.value = false
        getList()
      })
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("状态修改成功")
    }).catch(() => { })
  } else {
    proxy.$modal.confirm('是否确认启用护理计划编号为"' + _ids + '"的数据项？').then(function () {
      updateLevel(updateForm.value).then(response => {
        proxy.$modal.msgSuccess("修改成功")
        open.value = false
        getList()
      })
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("状态修改成功")
    }).catch(() => { })
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('level/level/export', {
    ...queryParams.value
  }, `level_${new Date().getTime()}.xlsx`)
}

getList()
getPlanList()
</script>
